import {
    url,
} from '@/lib/utils';
import {
    api,
} from '@/lib/api';

import { Module } from 'vuex';
import { RootState } from '@/types/store';
export interface FrameworkState {}

const m: Module<FrameworkState, RootState> = {
    namespaced: true,

    actions: {
        /**
         * 上传图片
         */
        async upload(context, { type, filePath }) {
            const res = await api.uploadFile({
                url: `${url}/api/upload`,
                filePath,
                name: 'image',
                formData: {
                    type,
                },
            }).catch(err => {
                // console.log(err);
            });
            return res;
        },
        /**
         * 直传阿里云配置
         */
        async uploadConfig(context, { type, ext }) {
            const res = await api.get({
                url: `${url}/api/upload_config`,
                data: {
                    type,
                    ext,
                },
            }).catch(err => {
                // console.log(err);
            });
            return res.data;
        },
        /**
         * 直传阿里云
         */
        async uploadImageToAliyun(context, { filename, uploadConfig }) {
            const data = {
                'key': uploadConfig.key,
                'OSSAccessKeyId': uploadConfig.accessKeyId,
                'policy': uploadConfig.policy,
                'Signature': uploadConfig.signature,
            };
            // console.log('uploadConfig', uploadConfig, data);
            const response = await api.uploadFile({
                url: uploadConfig.host,
                filePath: filename,
                name: 'file',
                formData: data,
            }).then((response) => {
                return {
                    status: 200,
                    data: {
                        status: 0,
                        message: 'OK',
                        data: {
                            key: uploadConfig.key,
                            url: uploadConfig.url,
                        },
                    },
                };
            }).catch((err) => {
                // console.log(err);
                return {
                    // 报错
                    status: 500,
                    data: {
                        status: -1,
                        message: '啊哦，上传出现了点小问题',
                        data: {
                            url: '',
                            key: '',
                        },
                    },
                };
            });
            return response.data;
        },
    },
};

export default m;
